<?php

namespace app\modules\backend\controllers;

use app\models\Base;
use app\models\Category;
use app\tools\Re;
use Yii;
use yii\helpers\Json;

class CateController extends BaseController
{
    /**
     * @param string $type
     * @return array
     */
    public function actionCateList(){
        $page = Yii::$app->request->post('page', 0);
        $name = Yii::$app->request->post('name', '');
        $type = Yii::$app->request->post('type', 1);
        $cate_query = Category::find()->where(['type' => $type, 'status' => [0,1]]);
        if ($name) {
            $cate_query->andWhere(['like', 'name', $name]);
        }
        $cate = $cate_query->orderBy("created_at desc")->limit(Category::PAGE_SIZE)->offset(Category::PAGE_SIZE*$page)->all();
        $cate_data = [];
        if ($cate) {
            foreach ($cate as $v) {
                $cate_data[] = [
                    'id' => $v->id,
                    'name' => $v->name,
                    'icon' => $v->icon,
                    'type' => $v->type,
                    'status' => $v->status,
                    'created_time' => date("Y-m-d H:i", $v->created_at),
                ];
            }
        }
        return Re::data([
            'data' => $cate_data,
            'totalPage' => $cate_query->count(),
            'currentPage' => $page,
            'perPage' => Category::PAGE_SIZE
        ]);
    }

    public function actionEditCate(){
        $id = Yii::$app->request->post('id', 0);
        $post = Yii::$app->request->post();
        $cate_old = Category::find()->where(['name' => $post['name'], 'type' => $post['type']])->andWhere("id <> '$id'")->one();
        if ($cate_old) {
            return Re::data(null, '分类信息已存在', Re::ERROR);
        }
        return $this->edit(Category::class, $id, $post);
    }

    public function actionChangeCateStatus(){
        $id = Yii::$app->request->post('id', 0);
        $status = Yii::$app->request->post('status', 0);
        $cate = Category::findOne($id);
        if (empty($cate)) {
            return Re::data(null, '分类信息读取失败', Re::ERROR);
        }
        $cate->status = $status;
        if (!$cate->save()) {
            return Re::data(null, '操作失败', Re::ERROR);
        }
        return Re::data();
    }

    public function actionListForSelect(){
        $type = Yii::$app->request->post('type', 1);
        $cate_list = Category::find()->where(['type' => $type, 'status' => 1])->select('id,name')->orderBy("created_at desc")->all();
        return Re::data(['data' => $cate_list]);
    }
}
